package utils

import okhttp3.*
import java.io.File
import java.net.URLEncoder
import java.util.concurrent.TimeUnit

object NetworkUtil {

    val client: OkHttpClient by lazy {
        OkHttpClient.Builder()
                .connectTimeout(2000, TimeUnit.MILLISECONDS)
//                .addInterceptor(NeteaseInterceptor())
//                .addInterceptor(LogInterceptor())
                .build()
    }

    fun get(url: String): Response{
        val request = Request.Builder().url(url).get().build()
        return client.newCall(request).execute()
    }

    fun post(url: String, params: Map<String, String>): Response {
        val form = FormBody.Builder()
        for (entry in params) {
            form.add(entry.key, entry.value)
        }
        val request = Request.Builder()
                .post(form.build())
                .url(url)
                .build()
        return client.newCall(request).execute()
    }

    fun urlEncode(original: String): String {
        return URLEncoder.encode(original)
    }

    fun postJson(url: String, json: String): Response{
        val request = Request.Builder()
                .url(url)
                .post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), json))
                .build()
        return client.newCall(request).execute()
    }

}

/*
class LogInterceptor: Interceptor {

    val DEBUG = true
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        if (DEBUG){
            println("url = ${request.url()}")
            println("headers = ${request.headers()}")
        }
        return chain.proceed(request)
    }
}
*/

